<template>
  <div class="create-cost-dialog">
    <el-dialog
      :visible.sync="visible"
      :append-to-body="false"
      :before-close="handleCancel"
      class="dialog-size-auto small-common-dialog-size"
      width="450px">
      <div class="main">
        <Title title="新建链接" font-size="16px" style="margin-bottom:20px;"/>
        <el-form
          ref="createDataForm"
          :rules="rules"
          :model="form"
          label-position="right"
          label-width="90px"
          class="lineHeight32">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" :maxlength="50" class="width240" placeholder="请输入项目名称" size="small" />
          </el-form-item>
          <el-form-item label="采集链接" prop="collectUrl" class="rel">
            <div class="flex-center">
              <el-input v-model="form.collectUrl" :maxlength="500" class="width240" placeholder="请输入采集链接" size="small" @blur="checkSameLink(form.collectUrl)"/>
              <span v-if="existSameLink" class="error-text">当前链接已添加过报告，点击确定继续创建</span>
              <InfoIcon content="链接需含有http/https，否则判定为问题链接" style="width: 16px;height: 16px;margin-left: 4px;" />
            </div>
          </el-form-item>
          <el-form-item label="采集方式" prop="collectWay">
            <el-select v-model="form.collectWay" placeholder="请选择" class="width240" size="small" @change="changeCollectWays">
              <el-option
                v-for="item in collectWaysOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <template v-if="form.collectWay !== 0">
            <el-form-item v-for="(item, index) in form.collectDate" :key="item._uuid" :rules="rules.time" :prop="`collectDate.${index}.time`" label="采集日期">
              <div class="flex collect-date-box">
                <el-date-picker
                  v-model="item.time"
                  :picker-options="disabledDate(form.collectWay)?pickerOptions:null"
                  :class="{'width-diy':form.collectWay === 4 && index > 0}"
                  class="width240"
                  size="small"
                  format="yyyy/MM/dd"
                  value-format="timestamp"
                  placeholder="选择日期" />
                <div v-if="form.collectWay === 4" class="btns flex-center">
                  <template v-if="!showMobilePage">
                    <span v-if="index === form.collectDate.length-1" class="add-btn" @click="handleAdd">添加</span>
                    <span v-if="index > 0" class="del-btn" @click="handleDel(index)">删除</span>
                  </template>
                  <template v-else>
                    <div v-if="index > 0" class="del-btn" @click="handleDel(index)">
                      <i class="delete-icon el-icon-delete"/>
                    </div>
                  </template>
                </div>
              </div>
              <div v-if="showMobilePage && index === form.collectDate.length-1" class="add-btn-mobile" @click="handleAdd">添加<span class="add-icon">+</span></div>
            </el-form-item>
          </template>
        </el-form>
        <div class="btn-container">
          <el-button :loading="btnLoading" size="small" type="primary" @click="handleCreate">确定</el-button>
          <el-button type="info" class="cancel-btn-style" size="small" @click="handleCancel">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Title from '@/components/Title';
import { standardFormat } from '@/filters/date';
import { addLink, checkSameLink } from '@/api/publish';
import setWay from '@/views/publish/module/setWay';
import { mapState } from 'vuex';
export default {
  filters: { standardFormat },
  components: { Title },
  mixins: [setWay],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    preciseData: {
      type: Array,
      default() {
        return [];
      }
    },
    id: {
      type: String | Number,
      default: ''
    },
    time: {
      type: String,
      default: ''
    },
    isRowAdd: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateUrl = () => {
      return (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入采集链接'));
        }
        const reg = /(https?):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g;
        if (!reg.test(value)) {
          callback(new Error('请输入正确的链接'));
        } else { callback(); }
      };
    };
    return {
      form: {
        projectName: '',
        collectWay: '',
        collectUrl: '',
        collectDate: []
      },
      rules: {
        collectUrl: [{ required: true, trigger: 'blur', validator: validateUrl() }],
        collectWay: [{ required: true, trigger: 'change', message: '请选择采集方式' }],
        time: [{ required: true, trigger: 'change', message: '请选择采集日期' }]
      },
      btnLoading: false,
      existSameLink: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  methods: {
    handleCreate() {
      // 校验必填
      this.$refs['createDataForm'].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          this.$emit('btnStatus', true);
          const params = JSON.parse(JSON.stringify(this.form));
          params.collectDate = params.collectDate.map(item => {
            item = item.time / 1000;
            return item;
          });
          if (params.collectDate.length > 0) {
            // 对采集日期去重
            params.collectDate = [...new Set(params.collectDate)];
          }
          addLink(params).then(res => {
            this.btnLoading = false;
            this.$emit('updateData');
            this.$emit('btnStatus', false);
            this.handleCancel();
          }).catch(err => {
            this.btnLoading = false;
            console.log(err);
            this.$emit('btnStatus', false);
          });
        } else {
          return false;
        }
      });
    },
    checkSameLink(collectUrl) {
      this.existSameLink = false;
      if (!collectUrl) return;
      checkSameLink({ collectUrl }).then(res => {
        if (res.code === 200) {
          this.existSameLink = res.data.existSameLink;
        }
      }).catch(err => {
        console.log(err);
      });
    },
    handleCancel() {
      this.$refs['createDataForm'].resetFields();
      this.form.collectDate = [];
      this.$emit('closeDialog');
      this.existSameLink = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.width240 {
  width: 240px;
}
.create-cost-dialog {
  &::v-deep {
    .el-form-item {
      margin-bottom: 22px !important;
    }
  }
}
.btn-container {
  display: flex;
  justify-content: center;
}
.collect-date-box {
  .btns{
    font-size: 14px;
    cursor: pointer;
    .add-btn{
      margin-left: 12px;
      color: #406EFF;
      white-space: nowrap;
    }
    .del-btn{
      margin-left: 12px;
      color: #192452;
      white-space: nowrap;
    }
  }
}
.add-btn-mobile {
  color: #406EFF;
  .add-icon {
    font-size: 18px;
    margin-left: 8px;
    font-weight: bold;
  }
}
.error-text {
  position: absolute;
  top: 26px;
  left: 0;
  font-size: 12px;
  color: red;
}
</style>
